package com.csii.epaySandbox.controller;

import java.io.PrintWriter;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.csii.epaySandbox.entity.User;
import com.csii.epaySandbox.exception.DeptException;
import com.csii.epaySandbox.exception.PasswordException;
import com.csii.epaySandbox.exception.UserNotFoundException;
import com.csii.epaySandbox.service.DeptService;
import com.csii.epaySandbox.service.UserService;
import com.csii.epaySandbox.util.JsonResult;

@Controller
public class UserController extends AbstractController{
	
	@Resource
	private UserService userService;
	
	@Resource
	private DeptService deptService;
	
	@RequestMapping("/login.do")
	@ResponseBody
	public Object login(String username,String password,HttpSession session){
		System.out.println("用户名："+username+
								"密码："+password);
		User user = userService.login(username, password);
		//登录成功后，将user信息保存到session，用于在过滤器中检查登陆情况
		session.setAttribute("loginUser", user);
		//查询所有需要测试的机构信息
		List deptList = deptService.getDeptMsg();
		//将所有查出来的机构信息返回给页面
		if(deptList == null || deptList.size() <= 0){
			throw new DeptException("无可测试机构");
		}
		return new JsonResult(deptList);
	}
	
	@ExceptionHandler(UserNotFoundException.class)
	@ResponseBody
	public JsonResult handleUserNotFoundException(UserNotFoundException e){
		return new JsonResult(2,e);
	}
	
	@ExceptionHandler(PasswordException.class)
	@ResponseBody
	public JsonResult handlePasswordException(PasswordException e){
		return new JsonResult(3,e);
	}
	
	@ExceptionHandler(DeptException.class)
	@ResponseBody
	public JsonResult handleDeptNotFoundException(PasswordException e){
		return new JsonResult(4,e);
	}
}
